#!/usr/bin/python
import sys
import urllib2
import string

try:
    import pygtk
    pygtk.require("2.0")
except:
    pass
try:
    import gtk
    import gtk.glade
except:
    sys.exit(1)

class NappyGui:
    """holamon GTK app"""
    def __init__(self):
        self.gladefile="nappy-gui.glade"
        self.wTree=gtk.glade.XML(self.gladefile)
        self.window=self.wTree.get_widget("window")
        self.txtCity=self.wTree.get_widget("txtCity")
        self.txtAddress=self.wTree.get_widget("txtAddress")
        self.txtNumber=self.wTree.get_widget("txtNumber")
        self.txtLabel=self.wTree.get_widget("txtLabel")
        self.txtDescription=self.wTree.get_widget("txtDescription")
        self.txtLatitude=self.wTree.get_widget("txtLatitude")
        self.txtLongitude=self.wTree.get_widget("txtLongitude")
        if (self.window):
            self.window.connect("destroy",gtk.main_quit)
        
        #Create our dictionay and connect it
        dic = { "on_btncancel_clicked" : self.btnCancel_clicked,
                "on_btngetcoords_clicked" : self.btnGetCoords_clicked,
                "on_quit_button_clicked" : self.btnQuit_clicked,
                "on_MainWindow_destroy" : gtk.main_quit,
                "on_btnaddpoi_clicked" : self.btnAddPoi_clicked }
        self.wTree.signal_autoconnect(dic)    

   
    def btnCancel_clicked(self, widget):
        self.txtCity.set_text("")
        self.txtAddress.set_text("")
        self.txtNumber.set_text("")
        self.txtLabel.set_text("")
        self.txtDescription.set_text("")
        self.txtLatitude.set_text("")
        self.txtLongitude.set_text("")

    def btnGetCoords_clicked(self, widget):
        city=self.txtCity.get_text().replace(" ", "+")
        address=self.txtAddress.get_text().replace(" ", "+")
        number=self.txtNumber.get_text()
        poiadd=city + "+" + address + "+" + number
        self.label=self.txtLabel.get_text()
        self.description=self.txtDescription.get_text()
        # builds the url to pass to yahoo map service
        url = "http://api.local.yahoo.com/MapsService/V1/geocode?appid=capelinks&location=" + poiadd + "&Geocode=Geocode"        
        # sends the request and gets the response
        req = urllib2.Request(url)
        response = urllib2.urlopen(req)
        xml = response.read()
        # parses the results
        a = string.find(xml, "<Latitude>")
        b = string.find(xml, "<Longitude>")
        self.lat = xml[a+10:a+19]
        self.lon = xml[b+11:b+20]
        # write the results
        self.txtLatitude.set_text(self.lat)
        self.txtLongitude.set_text(self.lon)      	      
    
    def btnQuit_clicked(self, widget):
        gtk.main_quit()
  
    def btnAddPoi_clicked(self, widget):
        exists=""
        # set the strings to pass to MyPoi.txt file
        l_first = 'type="poi_viewpoint" label="' + self.label + '" description="' + self.description + '"'
        l_second = str(self.lon) + " " + str(self.lat)
        # check if the poi already exists
        fileHandle = open ( "/home/glider/opt/navit/navit/maps/MyPoi.txt" )
        fileList = fileHandle.readlines()
        fileHandle.close()
        for fileLine in fileList:
            if fileLine == l_second + '\n':
                exists="yes"
                break
        if exists=="yes":
            info = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, None)
            info.set_markup("Aborting: there is already a Poi with these coordinates!")
            info.show_all()
            info.run()
            info.destroy()
        else:
            # if it doesn't exist, inserts it to MyPoi.txt
            fileHandle = open ( "/home/glider/opt/navit/navit/maps/MyPoi.txt", 'a' )
            fileHandle.write ( l_first + '\n')
            fileHandle.write ( l_second + '\n')
            fileHandle.close()
            info = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, None)
            info.set_markup("New Poi added!")
            info.show_all()
            info.run()
            info.destroy()          
        #self.txtCity.set_text("ciao")
        #self.txtCity.get_text()
            

if __name__=="__main__":
    hol= NappyGui()
    gtk.main()


# address of MyPoi.txt file
#MyPoiFile = "~/opt/navit/navit/maps/MyPoi.txt"
#
 
#
 

#print l_first
#print l_second
#